import {
	groupDepth,
	groupMaxNumber
} from './constants.js'

const db = uniCloud.database();
const collection = db.collection('ha_group_list');

async function getChildGroupID(group_id,depth) {
	if ( depth >= groupDepth ) {
		return [];
	}

	let result = [];
	depth += 1;

	let res = await collection
		.where({
			parent_id: group_id
		})
		.get();

	for ( let i = 0; i < res.data.length; i++ ) {
		result.push(res.data[i]._id);

		if ( res.data[i].hasOwnProperty('is_split') == false || res.data[i].is_split != true ) {
			result = result.concat(await getChildGroupID(res.data[i]._id,depth));
		}
	}

	return result;
}

async function getFirstChildGroup(group_id) {
	let res = await collection
		.where({
			parent_id: group_id
		})
		.get();

	return res.data;
}

async function updateGroupParent(group_id,parent_id) {
	await collection
		.doc(group_id)
		.update({
			parent_id
		});
}

async function deleteOneGroup(group_id) {

	await db.collection('ha_group_person')
		.where({
			group_id
		})
		.remove();

	// await db.collection('ha_group_notice')
	// 	.where({
	// 		group_id
	// 	})
	// 	.remove();

	await db.collection('ha_report_list')
		.where({
			group_id
		})
		.remove();

	// await db.collection('ha_report_summary')
	// 	.where({
	// 		group_id
	// 	})
	// 	.remove();

	await collection
		.doc(group_id)
		.remove();
}

async function checkGroupNumber(account_id) {
	let res = await collection
		.where({
			account_id
		})
		.get();

	if (res.data && res.affectedDocs >= groupMaxNumber) {
		return false
	}
	return true;
}

async function checkGroupDepth(account_id,group_id) {
	// 1. 自己的团体
	// 2. 下属团体
	// 3. 最远端下属团体

	let res;
	for ( let i = 0; i <= groupDepth; i++ ) {
		res = await collection
			.doc(group_id)
			.get();

		if (res.data && res.affectedDocs === 1) {
			if (res.data[0].account_id == account_id) {
				if (i == 0) {
					return 1;
				} else if (i < groupDepth) {
					return 2;
				} else {
					return 3;
				}
			}
			group_id = res.data[0].parent_id;
		} else {
			return 0;
		}
	}
	return 0;
}

async function updateGroupItem(group_id,group_info) {
	await collection
		.doc(group_id)
		.update(group_info);
}

async function checkGroupItem(group_id,group_cond) {
	let res = await collection
		.where(Object.assign(group_cond,{
			_id: group_id
		}))
		.limit(1)
		.get();

	return (res.data && res.affectedDocs >= 1) ? true : false;
}

export default {
	getChildGroupID,
	getFirstChildGroup,
	updateGroupParent,
	deleteOneGroup,
	checkGroupNumber,
	checkGroupDepth,
	updateGroupItem,
	checkGroupItem
}